package com.mzy.NetworkProgram.TcpSocket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/6/8 21:15
 * @Version 1.0
 */
@Slf4j
public class SocketTcpServer {
    public static void main(String[] args) throws IOException {
        // 思路
        // 1.在本机 的9999端口监听，等待连接发送
        //      细节：要求在本机中没有其他服务在监听9999
        //      细节：这个ServerSocket 可以通过accept() ，返回多个Socket[多个客户端连接]
//        InetAddress byAddress = Inet4Address.getByAddress(new byte[]{(byte) 192, (byte) 168,0, (byte) 138});
        InetAddress byAddress = Inet4Address.getByAddress(new byte[]{(byte) 192, (byte) 168,32, (byte) 99});
        ServerSocket serverSocket = new ServerSocket(60000,50,byAddress) ;
        log.info("服务器，在{}端口监听{}服务，等待连接.....",serverSocket.getLocalPort(),serverSocket.getInetAddress());
        // 2.当没有客户端连接9999端口时，程序会阻塞，等待连接
        //      如果有客户端连接，则会返回Socket对象，程序继续
        Socket acceptSocket = serverSocket.accept();

        System.out.println("服务器 socket =" + acceptSocket.getClass() + acceptSocket.getInetAddress());

        //
        // 3. 通过socket.getInputStream() 读取
        //      客户端写入到数据通道的数据，显示
        InputStream inputStream = acceptSocket.getInputStream();
        // 4. IO读取
        byte[] bytes = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(bytes)) != -1) {
            System.out.println(new String(bytes,0,readLen));
        }
        // 5.关闭流和socket
        inputStream.close();
        serverSocket.close();
        // acceptSocket是每一个会话
        acceptSocket.close();
    }
}
